package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by 小可乐$ on 2024/8/13$ 9:32$
 * description:
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties properties;

    @Override
    public String uploadFile(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断桶是否存在
        boolean bucketed = minioClient.bucketExists(
                BucketExistsArgs
                        .builder()
                        .bucket(properties.getBucketName())
                        .build());
        if (!bucketed) {
//                声明创建一个桶
            minioClient.makeBucket(
                    MakeBucketArgs
                            .builder()
                            .bucket(properties.getBucketName())
                            .build());
//                更改桶的权限为全部人可读，只能自己写,bucket(桶名) config(权限字符串)
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(properties.getBucketName())
                            .config(createBucketPolicyConfig(properties.getBucketName()))
                            .build());
        }
//            上传到minio的图片命名方式
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date())
                + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//            上传文件uploadObject：只能上传本地磁盘的文件，putObject：上传流文件
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(properties.getBucketName())
                        .stream(file.getInputStream(), file.getSize(), -1)//文件流，文件大小，每次传输文件大小，-1为自动分配
                        .object(filename)
                        .contentType(file.getContentType())//流传输类型，按原文件类型传输，否则按流传输，会下载来下
                        .build());
//            返回拼接一个图片存储的地址路径,路径名/桶名/文件名
//            String url =properties.getEndpoint()+"/"+properties.getBucket()+"/"+filename;
        String url = String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);
        return url;
    }


/**
 * 声明一个桶权限字符串，全部人可读，只能自己写
 */
private String createBucketPolicyConfig(String bucketName) {

    return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
}
}
